/*
 * @Description: 请求数据
 * @Version: 1.0
 * @Author: tao
 * @Date: 2021-01-15 16:25:21
 * @LastEditors: tao
 * @LastEditTime: 2021-05-09 22:47:21
 */
import axios from 'axios'
import Vue from 'vue'
import store from 'store/index';

let loading = Vue.prototype.$message.loading;
let success = Vue.prototype.$message.success;
let error = Vue.prototype.$message.error;

let text = {
  loadTxt: '加载中',
  successTxt: '请求成功',
  errTxt: '请求失败'
}

//记录当前有多少个请求
let r = 0;
//请求加载动画
let hide = null;

 export const IP = "http://172.16.71.30:81"
//export const IP = "/api"


export function request(config, msg = {}, isFile = false) {
  msg = {
    ...text,
    ...msg
  }

  const instance = axios.create({
    baseURL: isFile ? IP : (IP + "/admin"),
    timeout: 5000
  });
  //1.发送请求前
  instance.interceptors.request.use(config => {

    if (r++ === 0) {
      hide = loading(msg.loadTxt, 0)
    }
    //判断请求是否为登录
    if (config.url == "/login/login") {
      return config;
    }
    // 设置请求头统一携带token
    config.headers.Authorization = store.getters.getToken
    return config;

  }, err => {
    //提示错误
    r = 0;
    hide()
    error(msg.errTxt, 1)
    console.log('发送请求前报错', err)
  })

  //2.接收数据后
  instance.interceptors.response.use(res => {
    if (--r === 0) {
      hide();
      !!msg.successTxt && success(msg.successTxt, 1)
    }
    return res.data
  }, err => {
    //提示错误
    r = 0;
    hide()
    error(msg.errTxt, 1)
    console.log('接收数据报错', err)
  })

  //3.真正发送网络请求
  return instance(config)
}